﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetworkSocket;
using NetworkSocket.WebSocket;

namespace Server
{
    /// <summary>
    /// WebSocket服务
    /// </summary>
    public class WebServer : WebSocketServerBase
    {
        /// <summary>
        /// 收到文本请求时出发
        /// </summary>
        /// <param name="client">客户端</param>
        /// <param name="text">内容</param>
        protected override void OnText(SocketAsync<Hybi13Packet> client, string text)
        {
            // 回复内容
            this.SendText(client, "->" + text);

            // 转发给其它客户端
            var others = this.AliveClients.Except(client);
            foreach (var item in others)
            {
                this.SendText(item, client.ToString() + "->" + text);
            }

            // ping此客户端，记录ping的时间
            client.TagBag.PingTime = DateTime.Now;
            this.SendPing(client, null);
        }

        protected override void OnBinary(SocketAsync<Hybi13Packet> client, byte[] bytes)
        {
            this.SendBinary(client, bytes);
        }

        // ping回复
        protected override void OnPong(SocketAsync<Hybi13Packet> client, byte[] bytes)
        {
            var timeSpan = DateTime.Now.Subtract((DateTime)client.TagBag.PingTime);
            Console.WriteLine("ping {0} 用时:{1}ms", client, timeSpan.TotalMilliseconds);
        }

        protected override bool CheckHandshake(SocketAsync<Hybi13Packet> client, HandshakeRequest request)
        {
            Console.WriteLine("{0}进行握手完成", client);
            return base.CheckHandshake(client, request);
        }

        protected override void OnConnect(SocketAsync<Hybi13Packet> client)
        {
            Console.WriteLine("客户{0}连接进来，当前连接数：{1}", client, this.AliveClients.Count);
        }

        protected override void OnDisconnect(SocketAsync<Hybi13Packet> client)
        {
            Console.WriteLine("{0}断开连接，当前连接数：{1}", client, this.AliveClients.Count);
        }
    }
}
